const path = require('path');
const { Client } = require('ssh2');
const { config: loadEnvConfig } = require('dotenv');

const ROOT_PATH = path.resolve(__dirname, '../');
const ENV_CONFIG_PATH = path.resolve(ROOT_PATH, '.env');
loadEnvConfig({ path: ENV_CONFIG_PATH });

const SSH_SERVER_HOST = process.env.SSH_SERVER_HOST;
const SSH_SERVER_PORT = process.env.SSH_SERVER_PORT;
const SSH_SERVER_USERNAME = process.env.SSH_SERVER_USERNAME;
const SSH_SERVER_PASSWORD = process.env.SSH_SERVER_PASSWORD;

const USER_NAME = process.env.USER_NAME;
const PROJ_NAME = process.env.PROJ_NAME;
const DEPLOY_PATH = process.env.DEPLOY_PATH;

function main() {
  const client = new Client();
  client
    .on('ready', () => {
      console.log('Client::ready');
      client.shell((err, channel) => {
        if (err) throw err;
        channel
          .on('close', () => {
            console.log('Channel::close');
            client.end();
          })
          .on('data', data => {
            console.log(`${data}`);
          });

        // 执行
        let destDir = DEPLOY_PATH;
        if (!destDir) {
          if (!USER_NAME && !PROJ_NAME) {
            console.log(
              'DEPLOY_PATH 不存在，同时 USER_NAME 与 PROJ_NAME 也不存在，请在 .env 中进行配置！',
            );
            process.exitCode = 1;
            return;
          }
          destDir = `/home/${USER_NAME}/${PROJ_NAME}`;
        }
        channel.end(`cd ${destDir}\ndocker-compose up -d\ndocker ps\nexit\n`);
      });
    })
    .connect({
      host: SSH_SERVER_HOST,
      port: SSH_SERVER_PORT,
      username: SSH_SERVER_USERNAME,
      password: SSH_SERVER_PASSWORD,
    });
}

main();
